package com.pi.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.alibaba.fastjson.JSONObject;
import com.pi.base.common.BaseResult;
import com.pi.base.constant.SysStatics;
import com.pi.base.entity.SysRole;
import com.pi.base.entity.SysUser;

/**
 * 基本的Controller
 * 时间格式转换：bean上增加 @JsonFormat(pattern="yyyy-MM-dd HH:mm",timezone = "GMT+8")
 * @author zoumy
 *
 */
public abstract class  BaseController{
	
	@ExceptionHandler
	public String exception(HttpServletRequest request, HttpServletResponse response, Exception e) { 
	     
	    //ajax请求
	     if (request.getHeader("accept").indexOf("application/json") > -1
	             || (request.getHeader("X-Requested-With")!= null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {
	        response.setStatus(500);
	        response.setContentType("application/json;charset=utf-8");  
	        try {
	        	e.printStackTrace();
	        	BaseResult result = BaseResult.newErrorResult(e);
	            PrintWriter writer = response.getWriter(); 
	            writer.write(JSONObject.toJSONString(result)); 
	            writer.flush(); 
	        } catch (IOException e1) {
	            e1.printStackTrace();
	        } 
	        return null;
	     }
	     else{//普通的网络请求
	        request.setAttribute("exceptionMessage", e.getMessage()); 
	         e.printStackTrace();
	        // 异常分类
	        if(e instanceof SQLException)
	            return "sqlerror";  
	        else
	            return "error"; 
	    }
	} 

	
	/**
	 * 获取当前登录用户
	 * @param httpSession
	 * @return
	 */
	public synchronized SysUser getLoginedUserInfo(HttpSession httpSession){
		return (SysUser) httpSession.getAttribute(SysStatics.WEB_USER_SESSION);
	}
	

	/**
	 * 获得当前登录User的Role
	 * 
	 * @return
	 */
	public synchronized SysRole getLoginedUserRoleInfo(HttpSession httpSession) {
		return (SysRole) httpSession.getAttribute(SysStatics.WEB_ROLE_SESSION);
	}
	
	public synchronized boolean isSupperAdmin(SysUser loginUser){
		if(SysStatics.SysUser_IsSuperAdmin == loginUser.getSuperadmin()){
			return true;
		}
		return false;
	}
	
	public synchronized boolean isSupperAdmin(HttpSession httpSession){
		SysUser loginUser = getLoginedUserInfo(httpSession);
		if(SysStatics.SysUser_IsSuperAdmin == loginUser.getSuperadmin()){
			return true;
		}
		return false;
	}
	
	public synchronized boolean isAdmin(HttpSession httpSession){
		SysUser loginUser = getLoginedUserInfo(httpSession);
		if(loginUser != null && SysStatics.SYSUSER_TYPE_ADMIN == loginUser.getType().intValue()){
			return true;
		}
		return false;
	}
}
